package com.team11.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.team11.server.config.security.JwtTokenUtil;
import com.team11.server.mapper.AdminMapper;
import com.team11.server.mapper.SInformationMapper;
import com.team11.server.mapper.TInformationMapper;
import com.team11.server.pojo.SInformation;
import com.team11.server.pojo.TInformation;
import com.team11.server.service.IAdminService;
import com.team11.server.pojo.Admin;
import com.team11.server.util.PasswordValidate;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import com.team11.server.pojo.dto.RespBean;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author pjc
 * @since 2021-06-13
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Resource
    private UserDetailsService userDetailsService;
    @Resource
    private PasswordEncoder passwordEncoder;
    @Resource
    private JwtTokenUtil jwtTokenUtil;
    @Value("${jwt.tokenHead}")
    private String tokenHead;
    @Resource
    private AdminMapper adminMapper;

    @Resource
    private TInformationMapper tInformationMapper;

    @Resource
    private SInformationServiceImpl sInformationService;

    @Resource
    private TInformationServiceImpl tInformationService;

    @Resource
    private SInformationMapper sInformationMapper;


    @Override
    public RespBean login(String username, String password, Integer roleIds, HttpServletRequest request) {
        int flag = 1;
        //第一次登录
        if (roleIds == 1 || roleIds == 0) {
            TInformation tInformation = tInformationService.getOne(new QueryWrapper<TInformation>().eq("t_job_number", username));
            if (tInformation == null) {
                return RespBean.error("用户名不正确!");
            }
            if (tInformation.getTState() == 0) {
                String substring = tInformation.getTIdNumber().substring(tInformation.getTIdNumber().length() - 6);
                String firstPassword = tInformation.getTJobNumber() + substring;
                if (!firstPassword.equals(password)) {
                    return RespBean.error("密码不正确!");
                } else {
                    Admin admin = new Admin();
                    admin.setRId(tInformation.getTJobNumber());
                    admin.setTType(1);
                    admin.setRPassword(passwordEncoder.encode(password));
                    admin.setState(true);
                    if (adminMapper.insert(admin) == 1) {
                        TInformation tInformation1 = new TInformation();
                        tInformation1.setTState(1);
                        tInformation1.setTId(tInformation.getTId());
                        tInformationMapper.updateById(tInformation1);
                        flag = 0;
                    }
                }
            }
        } else if (roleIds == 2) {
            SInformation sInformation = sInformationService.getOne(new QueryWrapper<SInformation>().eq("s_id", username));
            if (sInformation == null) {
                return RespBean.error("用户名不正确!");
            }
            if (sInformation.getSState() == 0) {
                String substring = sInformation.getSIdNumber().substring(sInformation.getSIdNumber().length() - 6);
                String firstPassword = sInformation.getSNumber() + substring;
                if (!firstPassword.equals(password)) {
                    return RespBean.error("密码不正确!");
                } else {
                    Admin admin = new Admin();
                    admin.setRId(sInformation.getSNumber());
                    admin.setTType(2);
                    admin.setRPassword(passwordEncoder.encode(password));
                    admin.setState(true);
                    if (adminMapper.insert(admin) == 1) {
                        SInformation sInformation1 = new SInformation();
                        sInformation1.setSState(1);
                        sInformation1.setSid(sInformation.getSid());
                        sInformationMapper.updateById(sInformation1);
                        flag = 0;
                    }
                }
            }
        }
        //登录
       UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
            return RespBean.error("用户名或密码不正确！");
        }
        if (!userDetails.isEnabled()) {
            return RespBean.error("账号被禁用，请联系管理员！");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                userDetails,
                null,
                userDetails.getAuthorities());

        SecurityContextHolder.getContext().setAuthentication(authenticationToken);  // 把token放在全局

        //生成token
        Integer type = getAdminByRId(username).getTType();
        Integer id = getAdminByRId(username).getId();
        String token = jwtTokenUtil.generateToken(userDetails);
        Map<String, Object> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("type", type);
        tokenMap.put("rid", id);
        tokenMap.put("flag", flag);
        return RespBean.success("登陆成功！", tokenMap);
    }

//        //登录
//        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
//
//        if (userDetails == null || !passwordEncoder.matches(password, userDetails.getPassword())) {
//            return RespBean.error("用户名或密码不正确！");
//        }
//        if (!userDetails.isEnabled()) {
//            return RespBean.error("账号被禁用，请联系管理员！");
//        }
//        Integer type = getAdminByRId(username).getTType();
//        Integer id = getAdminByRId(username).getId();
//
//        //更新security登录用户对象
//        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
//                userDetails,
//                null,
//                userDetails.getAuthorities()
//        );
//        SecurityContextHolder.getContext().setAuthentication(authenticationToken);  // 把token放在全局
//
//
//        //生成token
//        String token = jwtTokenUtil.generateToken(userDetails);
//        Map<String, Object> tokenMap = new HashMap<>();
//        tokenMap.put("token", token);
//        tokenMap.put("tokenHead", tokenHead);
//        tokenMap.put("type", type);
//        tokenMap.put("rid", id);
//        return RespBean.success("登陆成功！", tokenMap);
//    }

    @Override
    public Admin getAdminByRId(String username) {
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("r_id", username));
    }

    @Override
    public RespBean changPasswordById(Integer id, String newPassword, HttpServletRequest request) {
        String a = PasswordValidate.validatePassword(newPassword);
        if (!a.equals("1")) {
            return RespBean.error(a);
        }

        if (passwordEncoder.matches(newPassword,
                (adminMapper.selectOne(new QueryWrapper<Admin>().eq("id", id))).getPassword())) {
            return RespBean.error("新密码与原密码输入一致，请重新输入");
        }
        Admin admin = new Admin();
        admin.setRPassword(passwordEncoder.encode(newPassword));
        admin.setId(id);
        admin.setState(true);
        adminMapper.updateById(admin);
        return RespBean.success("修改成功!");
    }


}
